<!--
  智慧社区管理系统 - 物业费管理
  @author Wu.Liang
  @date 2024-01-01
  @updated 2025-01-21 - 完整实现物业费管理功能
-->
<template>
  <div class="property-fee-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-actions">
        <el-button type="primary" @click="handleCreate" :loading="creating">
          <el-icon><Plus /></el-icon>
          新增物业费
        </el-button>

      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="社区">
          <el-select
            v-model="searchForm.communityId"
            placeholder="请选择社区"
            clearable
            @change="handleCommunityChange"
            style="width: 200px"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.communityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋">
          <el-select
            v-model="searchForm.buildingId"
            placeholder="请选择楼栋"
            clearable
            @change="handleBuildingChange"
            style="width: 200px"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.buildingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单元">
          <el-select
            v-model="searchForm.unitId"
            placeholder="请选择单元"
            clearable
            @change="handleUnitChange"
            style="width: 200px"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房户">
          <el-select
            v-model="searchForm.householdId"
            placeholder="请选择房户"
            clearable
            @change="handleHouseholdChange"
            style="width: 200px"
          >
            <el-option
              v-for="item in householdList"
              :key="item.id"
              :label="item.roomNumber"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费状态">
          <el-select
            v-model="searchForm.paymentStatus"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="未缴费" :value="0" />
            <el-option label="已缴费" :value="1" />
            <el-option label="逾期" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">
          <span>物业费列表</span>
          <el-tag type="info" class="count-tag">共 {{ total }} 条记录</el-tag>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >

        <el-table-column prop="feeNo" label="收费单号" width="120" />
        <el-table-column prop="householdAddress" label="房户地址" min-width="250" />
        <el-table-column prop="billingPeriod" label="计费月份" width="120" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="{ row }">
            <span>¥{{ row.unitPrice || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="面积(㎡)" width="100">
          <template #default="{ row }">
            <span>{{ row.area || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="费用金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已支付金额" width="120">
          <template #default="{ row }">
            <span class="paid-amount">¥{{ row.paidAmount || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unpaidAmount" label="未支付金额" width="120">
          <template #default="{ row }">
            <span class="unpaid-amount">¥{{ row.unpaidAmount || row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="缴费状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.paymentStatus)" :effect="getStatusEffect(row.paymentStatus)">
              {{ row.paymentStatusName || getStatusName(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueDate" label="到期日期" width="120" />
        <el-table-column prop="paymentTime" label="缴费时间" width="160">
          <template #default="{ row }">
            <span v-if="row.paymentTime">{{ formatDateTime(row.paymentTime) }}</span>
            <span v-else class="text-muted">未缴费</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button 
                v-if="canUpdate && row.paymentStatus !== 1" 
                type="primary" 
                size="small" 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0 && canUpdate" 
                type="success" 
                size="small" 
                @click="handlePay(row)"
              >
                缴费
              </el-button>
              <el-button 
                v-if="row.paymentStatus === 0 && canUpdate" 
                type="warning" 
                size="small" 
                @click="handleReminder(row)"
              >
                催缴
              </el-button>
              <el-button size="small" @click="handleView(row)">查看</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="物业费详情"
      width="1000px"
    >
      <el-tabs v-model="detailTab" @tab-click="handleDetailTabClick">
        <el-tab-pane label="基本信息" name="base">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收费单号">{{ currentFee?.feeNo }}</el-descriptions-item>
            <el-descriptions-item label="房户地址">{{ currentFee?.householdAddress }}</el-descriptions-item>
            <el-descriptions-item label="计费月份">{{ currentFee?.billingPeriod }}</el-descriptions-item>
            <el-descriptions-item label="费用类型">
              <el-tag :type="getFeeTypeTagType(currentFee?.feeType)" :effect="getStatusEffect(currentFee?.feeType)">
                {{ getFeeTypeName(currentFee?.feeType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="单价" v-if="currentFee?.feeType === 0">¥{{ currentFee?.unitPrice || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="固定金额" v-if="currentFee?.feeType === 1">¥{{ currentFee?.fixedAmount || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="面积" v-if="currentFee?.feeType === 0">{{ currentFee?.area || '0.00' }} ㎡</el-descriptions-item>
            <el-descriptions-item label="费用金额">¥{{ currentFee?.amount }}</el-descriptions-item>
            <el-descriptions-item label="已支付金额">¥{{ currentFee?.paidAmount || '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="未支付金额">¥{{ currentFee?.unpaidAmount || currentFee?.amount }}</el-descriptions-item>
            <el-descriptions-item label="到期日期">{{ currentFee?.dueDate }}</el-descriptions-item>
            <el-descriptions-item label="缴费状态">
              <el-tag :type="getStatusTagType(currentFee?.paymentStatus)" :effect="getStatusEffect(currentFee?.paymentStatus)">
                {{ currentFee?.paymentStatusName || getStatusName(currentFee?.paymentStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="缴费时间" v-if="currentFee?.paymentTime">
              {{ formatDateTime(currentFee.paymentTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="支付方式" v-if="currentFee?.paymentMethod">
              {{ getPaymentMethodName(currentFee.paymentMethod) }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(currentFee?.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间" v-if="currentFee?.updateTime">{{ formatDateTime(currentFee.updateTime) }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ currentFee?.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="催缴/沟通" name="reminder" v-if="currentFee">
          <ReminderRecordPanel
            :feeId="Number(currentFee.id)"
            :feeType="0"
            :canEdit="canUpdate && currentFee.paymentStatus !== 1"
            ref="reminderPanelRef"
            @sync-success="handleSyncSuccess"
          />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑物业费"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="120px"
      >
        <el-form-item label="收费单号">
          <el-input v-model="editForm.feeNo" disabled />
        </el-form-item>
        <el-form-item label="房户地址">
          <el-input v-model="editForm.householdAddress" disabled />
        </el-form-item>
        <el-form-item label="计费月份">
          <el-input v-model="editForm.billingPeriod" disabled />
        </el-form-item>
        <el-form-item label="费用类型" prop="feeType">
          <el-select
            v-model="editForm.feeType"
            placeholder="请选择费用类型"
            style="width: 100%"
            @change="handleEditFeeTypeChange"
          >
            <el-option label="按面积计费" :value="0" />
            <el-option label="固定费用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item 
          :label="editForm.feeType === 0 ? '单价(元/㎡)' : '固定金额(元)'" 
          :prop="editForm.feeType === 0 ? 'unitPrice' : 'fixedAmount'"
        >
          <el-input-number
            v-if="editForm.feeType === 0"
            v-model="editForm.unitPrice"
            :precision="2"
            :min="0"
            style="width: 100%"
            placeholder="请输入单价"
            @change="handleEditAmountChange"
          />
          <el-input-number
            v-else-if="editForm.feeType === 1"
            v-model="editForm.fixedAmount"
            :precision="2"
            :min="0"
            style="width: 100%"
            placeholder="请输入固定金额"
            @change="handleEditAmountChange"
          />
        </el-form-item>
        <el-form-item label="面积(㎡)" v-if="editForm.feeType === 0">
          <el-input v-model="editForm.area" disabled />
        </el-form-item>
        <el-form-item label="费用金额" prop="amount">
          <el-input-number
            v-model="editForm.amount"
            :precision="2"
            :min="0"
            style="width: 100%"
            placeholder="费用金额"
            disabled
          />
        </el-form-item>
        <el-form-item label="到期日期" prop="dueDate">
          <el-date-picker
            v-model="editForm.dueDate"
            type="date"
            placeholder="选择到期日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            disabled
          />
        </el-form-item>
        <el-form-item label="缴费状态" prop="paymentStatus">
          <el-select
            v-model="editForm.paymentStatus"
            placeholder="请选择缴费状态"
            style="width: 100%"
          >
            <el-option label="未缴费" :value="0" />
            <el-option label="已缴费" :value="1" />
            <el-option label="逾期" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editing">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 新增物业费对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增物业费"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="社区" prop="communityId">
          <el-select
            v-model="formData.communityId"
            placeholder="请选择社区"
            style="width: 100%"
            @change="handleFormCommunityChange"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.communityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="计费月份" prop="billingMonthRange">
          <el-date-picker
            v-model="formData.billingMonthRange"
            type="monthrange"
            placeholder="选择计费月份时间段"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 100%"
            range-separator="~"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          />
        </el-form-item>
        <el-form-item label="到期日期" prop="dueDate">
          <el-date-picker
            v-model="formData.dueDate"
            type="date"
            placeholder="选择到期日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 物业费管理页面
 * @author Wu.Liang
 * @date 2025-01-21
 */
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Refresh, Download, Search } from '@element-plus/icons-vue'
import { propertyFeeApi } from '@/api/property'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'
import ReminderRecordPanel from './components/ReminderRecordPanel.vue'
import { ref as vueRef, nextTick } from 'vue'
const detailTab = vueRef<string>('base')
const reminderPanelRef = vueRef()
function handleDetailTabClick(tab: { paneName: string }) {
  if (tab.paneName === 'reminder' && reminderPanelRef.value) {
    nextTick(() => {
      reminderPanelRef.value.fetchReminders && reminderPanelRef.value.fetchReminders();
    });
  }
}

import { useUserStore } from '@/store/user'
import { formatDateTime } from '@/utils'
import { showMessage } from '@/utils/message'
import { PermissionComputedManager } from '@/utils/permission'

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const generating = ref(false)
const submitting = ref(false)
const editing = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const dialogType = ref<'create' | 'edit'>('create')
const selectedRows = ref<any[]>([])
const currentFee = ref<any>(null)
const dateRange = ref<string[]>([])


// 表格数据
const tableData = ref<any[]>([])
const total = ref(0)
const pagination = reactive({
  current: 1,
  size: 20
})

// 搜索表单
const searchForm = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  householdId: undefined as number | undefined,
  paymentStatus: undefined as number | undefined,
  billingPeriod: ''
})

// 区域数据
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])
const householdList = ref<any[]>([])

// 表单数据
const formRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const formData = reactive({
  id: undefined as number | undefined,
  communityId: undefined as number | undefined,
  billingMonthRange: [] as string[], // 新增：计费月份时间段
  dueDate: '', // 新增：到期日期
  remark: ''
})

// 编辑表单数据
const editForm = reactive({
  id: undefined as number | undefined,
  feeNo: '',
  householdAddress: '',
  billingPeriod: '',
  feeType: undefined as number | undefined,
  unitPrice: 2.50,
  fixedAmount: 200.00,
  area: 0,
  amount: undefined as number | undefined,
  dueDate: '',
  paymentStatus: 0
})

// 表单验证规则
const formRules: FormRules = {
  communityId: [{ required: true, message: '请选择社区', trigger: 'change' }],
  billingMonthRange: [{ type: 'array', required: true, message: '请选择计费月份时间段', trigger: 'change' }],
  dueDate: [{ required: true, message: '请选择到期日期', trigger: 'change' }]
}

// 编辑表单验证规则
const editFormRules: FormRules = {
  feeType: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
  unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  fixedAmount: [{ required: true, message: '请输入固定金额', trigger: 'blur' }],
  amount: [
    { required: true, message: '请输入费用金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '费用金额不能小于0', trigger: 'blur' } // 修复：改为min: 0，避免0值验证错误
  ],
  dueDate: [{ required: true, message: '请选择到期日期', trigger: 'change' }],
  paymentStatus: [{ required: true, message: '请选择缴费状态', trigger: 'change' }]
}

// 选项数据
const communityList = ref<any[]>([])

// 用户权限相关
const userStore = useUserStore()
const isSuperAdmin = computed(() => userStore.isSuperAdmin())
const hasPropertyCompany = computed(() => userStore.checkUserHasPropertyCompany())
const canUpdate = computed(() => isSuperAdmin.value || hasPropertyCompany.value)

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'create' ? '新增物业费' : '编辑物业费'
})

// 获取费用类型标签类型
const getFeeTypeTagType = (feeType: number) => {
  const types: { [key: number]: string } = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return types[feeType] || 'info'
}

// 获取费用类型名称
const getFeeTypeName = (feeType: number) => {
  const names: { [key: number]: string } = {
    0: '按面积计费',
    1: '固定费用'
  }
  return names[feeType] || '未知类型'
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  const types: { [key: number]: string } = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态效果
const getStatusEffect = (status: number) => {
  return status === 2 ? 'dark' : 'light'
}

// 获取状态名称
const getStatusName = (status: number) => {
  const names: { [key: number]: string } = {
    0: '未缴费',
    1: '已缴费',
    2: '逾期'
  }
  return names[status] || '未知状态'
}

// 获取支付方式名称
const getPaymentMethodName = (method: string | number) => {
  const methods: { [key: string]: string } = {
    '1': '现金',
    '2': '微信',
    '3': '支付宝',
    '4': '银行卡',
    'cash': '现金',
    'wechat': '微信',
    'alipay': '支付宝',
    'bank': '银行卡'
  }
  return methods[method?.toString()] || '未知方式'
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params: any = {
      current: pagination.current,
      size: pagination.size,
      billingPeriod: searchForm.billingPeriod
    }
    
    if (searchForm.communityId) params.communityId = searchForm.communityId
    if (searchForm.buildingId) params.buildingId = searchForm.buildingId
    if (searchForm.unitId) params.unitId = searchForm.unitId
    if (searchForm.householdId) params.householdId = searchForm.householdId
    if (searchForm.paymentStatus !== undefined) params.paymentStatus = searchForm.paymentStatus
    
    const response = await propertyFeeApi.getPropertyFeeList(params)
    if (response.code === 200) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    showMessage({ type: 'error', message: '加载数据失败' })
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    householdId: undefined,
    paymentStatus: undefined,
    billingPeriod: ''
  })
  buildingList.value = []
  unitList.value = []
  householdList.value = []
  pagination.current = 1
  loadData()
}

// 社区变化处理
const handleCommunityChange = async (communityId: number) => {
  searchForm.buildingId = undefined
  searchForm.unitId = undefined
  searchForm.householdId = undefined
  buildingList.value = []
  unitList.value = []
  householdList.value = []
  
  if (communityId) {
    try {
      const response = await buildingApi.getBuildingsByCommunity(communityId)
      buildingList.value = (response.data || []).filter((item: any) => item && item.id != null)
    } catch (error) {
      console.error('加载楼栋列表失败:', error)
      showMessage({ type: 'error', message: '加载楼栋列表失败' })
      buildingList.value = []
    }
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number) => {
  searchForm.unitId = undefined
  searchForm.householdId = undefined
  unitList.value = []
  householdList.value = []
  
  if (buildingId) {
    try {
      const response = await unitApi.getUnitsByBuilding(buildingId)
      unitList.value = (response.data || []).filter((item: any) => item && item.id != null)
    } catch (error) {
      console.error('加载单元列表失败:', error)
      showMessage({ type: 'error', message: '加载单元列表失败' })
      unitList.value = []
    }
  }
}

// 单元变化处理
const handleUnitChange = async (unitId: number) => {
  searchForm.householdId = undefined
  householdList.value = []
  
  if (unitId) {
    try {
      const response = await unitApi.getUnitHouseholds(unitId)
      householdList.value = (response.data || []).filter((item: any) => item && item.id != null)
    } catch (error) {
      console.error('加载房户列表失败:', error)
      showMessage({ type: 'error', message: '加载房户列表失败' })
      householdList.value = []
    }
  }
}

// 房户变化处理
const handleHouseholdChange = (householdId: number) => {
  // 房户选择变化时，可以在这里添加额外的逻辑
  // 目前只需要触发搜索即可
  console.log('房户选择变化:', householdId)
}

// 表单社区变化处理
const handleFormCommunityChange = (communityId: number) => {
  // 重置表单中的其他字段
  formData.feeType = undefined
  formData.unitPrice = 2.50 // 修复：保持默认单价
  formData.fixedAmount = 200.00 // 修复：保持默认固定金额
  formData.billingMonthRange = [] // 重置计费月份时间段
  formData.dueDate = '' // 重置到期日期
  formData.remark = ''
}



// 编辑表单费用类型变化处理
const handleEditFeeTypeChange = (feeType: number) => {
  editForm.feeType = feeType
  handleEditAmountChange()
}

// 编辑表单金额变化处理
const handleEditAmountChange = () => {
  if (editForm.feeType === 0) {
    // 按面积计费：金额 = 单价 × 面积
    editForm.amount = (editForm.unitPrice || 0) * (editForm.area || 0)
  } else if (editForm.feeType === 1) {
    // 固定费用：金额 = 固定金额
    editForm.amount = editForm.fixedAmount || 0
  }
}

// 日期范围变化
const handleDateRangeChange = () => {
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 新增
const handleCreate = () => {
  dialogType.value = 'create'
  resetForm()
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentFee.value = row
  viewDialogVisible.value = true
}

// 缴费
const handlePay = async (row: any) => {
  try {
    // 检查支付状态
    if (row.paymentStatus === 1) {
      showMessage({ type: 'warning', message: '该费用已支付，无需重复缴费' })
      return
    }
    
    // 确认缴费
    await ElMessageBox.confirm(
      `确认缴纳物业费：${row.feeNo}，金额：¥${row.amount}？`,
      '确认缴费',
      {
        confirmButtonText: '确认缴费',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用缴费API
    const billId = Number(row.id)
    if (!billId || isNaN(billId)) {
      showMessage({ type: 'error', message: '无效的账单ID' })
      return
    }
    
    const response = await propertyFeeApi.payPropertyFee(billId, {
      paymentAmount: row.amount,
      paymentMethod: 'online' // 在线支付
    })
    
    if (response.success) {
      showMessage({ type: 'success', message: '缴费成功' })
      // 刷新列表
      await loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '缴费失败' })
    }
  } catch (error: any) {
    if (error === 'cancel') {
      return
    }
    console.error('缴费失败:', error)
    showMessage({ type: 'error', message: error.message || '缴费失败' })
  }
}

// 催缴
const handleReminder = async (row: any) => {
  try {
    // 检查支付状态
    if (row.paymentStatus === 1) {
      showMessage({ type: 'warning', message: '该费用已支付，无需催缴' })
      return
    }
    
    // 确认催缴
    await ElMessageBox.confirm(
      `确认发送催缴通知给住户：${row.householdAddress}？`,
      '确认催缴',
      {
        confirmButtonText: '确认催缴',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用催缴API（修正：传入账单ID与提醒方式字符串，避免对象拼接到URL）
    const response = await propertyFeeApi.sendReminder(Number(row.id), 'sms')
    
    if (response.success) {
      showMessage({ type: 'success', message: '催缴通知发送成功' })
    } else {
      showMessage({ type: 'error', message: response.message || '催缴通知发送失败' })
    }
  } catch (error: any) {
    if (error === 'cancel') {
      return
    }
    console.error('催缴失败:', error)
    showMessage({ type: 'error', message: error.message || '催缴失败' })
  }
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    // 先获取完整的物业费详情数据
    const response = await propertyFeeApi.getPropertyFeeDetail(row.id)
    if (response.data) {
      currentFee.value = response.data
      Object.assign(editForm, {
        id: response.data.id,
        feeNo: response.data.feeNo || '',
        householdAddress: response.data.householdAddress || '',
        billingPeriod: response.data.billingPeriod || '',
        feeType: response.data.feeType,
        unitPrice: response.data.unitPrice !== undefined && response.data.unitPrice !== null ? Number(response.data.unitPrice) : 2.50,
        fixedAmount: response.data.fixedAmount !== undefined && response.data.fixedAmount !== null ? Number(response.data.fixedAmount) : 200.00,
        area: response.data.area !== undefined && response.data.area !== null ? Number(response.data.area) : 0,
        amount: response.data.amount !== undefined && response.data.amount !== null ? Number(response.data.amount) : 0,
        dueDate: response.data.dueDate || '',
        paymentStatus: response.data.paymentStatus
      })
    } else {
      // 如果获取详情失败，使用列表数据
      currentFee.value = row
      Object.assign(editForm, {
        id: row.id,
        feeNo: row.feeNo,
        householdAddress: row.householdAddress,
        billingPeriod: row.billingPeriod,
        feeType: row.feeType,
        unitPrice: row.unitPrice !== undefined && row.unitPrice !== null ? Number(row.unitPrice) : 2.50,
        fixedAmount: row.fixedAmount !== undefined && row.fixedAmount !== null ? Number(row.fixedAmount) : 200.00,
        area: row.area !== undefined && row.area !== null ? Number(row.area) : 0,
        amount: row.amount !== undefined && row.amount !== null ? Number(row.amount) : 0,
        dueDate: row.dueDate || '',
        paymentStatus: row.paymentStatus
      })
    }
    
    // 确保费用金额正确计算
    handleEditAmountChange()
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取物业费详情失败:', error)
    // 获取详情失败时，使用列表数据
    currentFee.value = row
    Object.assign(editForm, {
      id: row.id,
      feeNo: row.feeNo,
      householdAddress: row.householdAddress,
      billingPeriod: row.billingPeriod,
      feeType: row.feeType,
      unitPrice: row.unitPrice !== undefined && row.unitPrice !== null ? Number(row.unitPrice) : 2.50,
      fixedAmount: row.fixedAmount !== undefined && row.fixedAmount !== null ? Number(row.fixedAmount) : 200.00,
      area: row.area !== undefined && row.area !== null ? Number(row.area) : 0,
      amount: row.amount !== undefined && row.amount !== null ? Number(row.amount) : 0,
      dueDate: row.dueDate || '',
      paymentStatus: row.paymentStatus
    })
    handleEditAmountChange()
    editDialogVisible.value = true
  }
}

// 编辑提交
const handleEditSubmit = async () => {
  try {
    await editFormRef.value?.validate()
    editing.value = true
    
    // 确保amount字段有值且大于0
    if (!editForm.amount || editForm.amount <= 0) {
      showMessage({ type: 'error', message: '请输入有效的费用金额' })
      return
    }
    
    // 修复：提交包含费用类型的字段（到期日期不允许修改）
    const submitData = {
      amount: editForm.amount,
      // dueDate: editForm.dueDate, // 注释：到期日期不允许修改
      paymentStatus: editForm.paymentStatus,
      feeType: editForm.feeType,
      unitPrice: editForm.unitPrice
    }
    
    const response = await propertyFeeApi.editPropertyFee(editForm.id!, submitData)
    
    if (response.code === 200) {
      showMessage({ type: 'success', message: '编辑成功' })
      editDialogVisible.value = false
      loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '编辑失败' })
    }
  } catch (error) {
    console.error('编辑失败:', error)
    showMessage({ type: 'error', message: '编辑失败' })
  } finally {
    editing.value = false
  }
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条物业费记录吗？', '提示', {
      type: 'warning'
    })
    
    const response = await propertyFeeApi.deletePropertyFee(row.id)
    if (response.code === 200) {
      showMessage({ type: 'success', message: '删除成功' })
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    showMessage({ type: 'warning', message: '请选择要删除的记录' })
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条记录吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 获取选中的ID列表
    const ids = selectedRows.value.map(row => row.id)
    
    // 调用批量删除API
    const response = await propertyFeeApi.batchDeletePropertyFees(ids)
    
    if (response.success) {
      showMessage({ type: 'success', message: '批量删除成功' })
      // 清空选中状态
      selectedRows.value = []
      // 刷新列表
      await loadData()
    } else {
      showMessage({ type: 'error', message: response.message || '批量删除失败' })
    }
  } catch (error: any) {
    if (error === 'cancel') return
    console.error('批量删除失败:', error)
    showMessage({ type: 'error', message: error.message || '批量删除失败' })
  }
}



// 导出
const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = ElLoading.service({
      lock: true,
      text: '正在导出数据...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    // 构建导出参数
    const exportParams = {
      ...queryParams.value,
      pageSize: 10000, // 导出时获取更多数据
      pageNum: 1
    }
    
    // 调用导出API
    const response = await propertyFeeApi.exportPropertyFees(exportParams)
    
    if (response.success && response.data) {
      // 创建下载链接
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `物业费管理_${new Date().toISOString().slice(0, 10)}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      showMessage({ type: 'success', message: '导出成功，文件已下载' })
    } else {
      showMessage({ type: 'error', message: response.message || '导出失败' })
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    showMessage({ type: 'error', message: error.message || '导出失败' })
  } finally {
    // 关闭加载状态
    ElLoading.service().close()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'create') {
      // 验证计费月份时间段
      if (!formData.billingMonthRange || formData.billingMonthRange.length !== 2) {
        showMessage({ type: 'warning', message: '请选择计费月份时间段' })
        return
      }
      
      // 验证到期日期
      if (!formData.dueDate) {
        showMessage({ type: 'warning', message: '请选择到期日期' })
        return
      }
      
      // 生成一份包含时间段的总费用单
      const submitData: any = {
        communityId: formData.communityId!,
        billingMonthRange: formData.billingMonthRange,
        dueDate: formData.dueDate,
        remark: `计费时间段：${formData.billingMonthRange[0]} ~ ${formData.billingMonthRange[1]}`
      }
      
      try {
        const response = await propertyFeeApi.generatePropertyFee(submitData)
        if (response.code === 200) {
          const generatedCount = response.data || 0
          showMessage({ type: 'success', message: `成功生成${generatedCount}条物业费记录` })
          dialogVisible.value = false
          loadData()
        } else {
          showMessage({ type: 'error', message: `生成物业费失败: ${response.message}` })
        }
      } catch (error) {
        console.error('生成物业费失败:', error)
        showMessage({ type: 'error', message: '生成物业费失败，请检查参数是否正确' })
      }
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    showMessage({ type: 'error', message: '提交失败，请检查表单数据' })
  } finally {
    submitting.value = false
  }
}

// 生成月份范围
const generateMonthRange = (startMonth: string, endMonth: string): string[] => {
  const months: string[] = []
  const start = new Date(startMonth + '-01')
  const end = new Date(endMonth + '-01')
  
  let current = new Date(start)
  while (current <= end) {
    const year = current.getFullYear()
    const month = String(current.getMonth() + 1).padStart(2, '0')
    months.push(`${year}-${month}`)
    
    current.setMonth(current.getMonth() + 1)
  }
  
  return months
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    communityId: undefined,
    billingMonthRange: [], // 重置计费月份时间段
    dueDate: '', // 重置到期日期
    remark: ''
  })
}

// 对话框关闭
const handleDialogClose = () => {
  resetForm()
}

// 加载社区列表
const loadCommunityList = async () => {
  try {
    const response = await communityApi.getCommunityList({})
    if (response.code === 200) {
      // 过滤掉没有有效id的数据
      communityList.value = (response.data || []).filter((item: any) => item.id != null)
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    showMessage({ type: 'error', message: '加载社区列表失败' })
  }
}

// 同步成功事件处理
const handleSyncSuccess = () => {
  viewDialogVisible.value = false;
  loadData();
};


// 初始化
onMounted(async () => {
  try {
    // 1. 首先加载用户权限信息
    await userStore.getUserDataScope()
    
    // 2. 然后并行加载业务数据
    await Promise.all([
      loadData(),
      loadCommunityList()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    showMessage({ type: 'error', message: '初始化数据失败' })
  }
})
</script>

<style scoped lang="scss">
.property-fee-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 500;
      color: var(--text-primary);
    }
    
    .page-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .table-title {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 16px;
        font-weight: 500;
        
        .count-tag {
          font-size: 12px;
        }
      }
    }
    
    .amount {
      color: var(--success-color);
      font-weight: 500;
    }

    .paid-amount {
      color: var(--success-color);
      font-weight: 500;
    }

    .unpaid-amount {
      color: var(--warning-color);
      font-weight: 500;
    }
    
    .text-muted {
      color: var(--text-secondary);
    }
    
    .operation-buttons {
      display: flex;
      gap: 5px;
      flex-wrap: wrap;
      
      .el-button {
        margin: 0;
        padding: 5px 8px;
        font-size: 12px;
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}
</style>

